package com.snailct.bpp.router.impl;
import com.snailct.bpp.router.api.IServiceRouter;
import com.snailct.bpp.router.datachange.SynDealWithMessage;
import com.snailct.bpp.router.datachange.service.AcceptMessage;
import com.snailct.bpp.router.IServiceHandler;
import com.snailct.bpp.router.factory.ServiceFactory;
import com.snailct.bpp.service.core.definition.ServiceDefinition;
import com.snailct.bpp.service.core.handle.ServiceDefinitionHolder;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;

@Service("xmlServiceRouter")
public class XmlServiceRouter implements IServiceRouter {
    private static final Log logger = LogFactory.getLog(XmlServiceRouter.class);
    public String acceptRequest(String reqData) {
        String xmlStr = reqData;


        if(StringUtils.isEmpty(xmlStr)){
            logger.error("accept xml can't be null!");
            return "-1";
        }
        boolean isMessage = false;
        String mingXmlStr = "";
        try{
            //DES解密
            mingXmlStr = xmlStr;
            isMessage = true;
        }catch (Exception e){
            isMessage = false;
            e.printStackTrace();
        }
        //解密正常
        if(isMessage){
            boolean checkXMLlg = false;
            boolean checkXMLSchema = false;
            //验证报文格式
            checkXMLlg = true;
            checkXMLSchema = true;

            //如果报文合法
            if(checkXMLlg&&checkXMLSchema){
                //如果同步处理
                if(SynDealWithMessage.isSyn(mingXmlStr)){

                    ServiceDefinitionHolder definitionHolder = new ServiceDefinitionHolder();
                    ServiceDefinition serviceDefinition = definitionHolder.handle(mingXmlStr);
                    IServiceHandler serviceHandler = ServiceFactory.getServiceHandlerInstance(serviceDefinition);
                    return serviceHandler.handleService(serviceDefinition);
                }else{//异步处理
                    AcceptMessage accept = new AcceptMessage();
                    accept.setXmlStr(mingXmlStr);
                    accept.insertXMLStr();
                    return "1";
                }
            }
        }
        return null;
    }
}
